using System.Text.Json;
using System.Transactions;
using Mathmall.Administration.common;
using Mathmall.Administration.Mapper;
using Mathmall.Administration.Models;
using Mathmall.Administration.Vo;
using Microsoft.EntityFrameworkCore;

namespace Mathmall.Administration.Service.impl;

public class AttrService : IAttrService
{
    private readonly AttrMapper _attrMapper;
    private readonly IAttrAttrGroupRelationService _attrAttrGroupRelationService;
    private readonly ICategoryService _categoryService;
    private readonly IAttrGroupService _attrGroupService;

    public AttrService(AttrMapper attrMapper, IAttrAttrGroupRelationService attrAttrGroupRelationService,
        ICategoryService categoryService, IAttrGroupService attrGroupService)
    {
        _attrMapper = attrMapper;
        _attrAttrGroupRelationService = attrAttrGroupRelationService;
        _categoryService = categoryService;
        _attrGroupService = attrGroupService;
    }

    /// <summary>
    /// 保存属性信息
    /// </summary>
    /// <param name="attrVo"></param>
    /// <returns></returns>
    public async Task<int> AddAttr(AttrVo attrVo)
    {
        using (TransactionScope transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            // 将属性值集合转换为字符串
            Attr attr = JsonSerializer.Deserialize<Attr>(JsonSerializer.Serialize(attrVo))!;
            attr.ValueSelect = string.Join(";", attrVo.AttrValue);
            int id = await _attrMapper.AddAttr(attr);

            // 保存属性与属性分组的关联关系
            AttrAttrgroupRelation attrAttrgroupRelation = new AttrAttrgroupRelation()
                { AttrID = id, AttrGroupID = attrVo.AttrGroupID };
            int result = await _attrAttrGroupRelationService.AddAttrAttrGroupRelation(attrAttrgroupRelation);

            transactionScope.Complete();
            return result;
        }
    }

    /// <summary>
    /// 分页查询属性
    /// </summary>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="catalogID"></param>
    /// <param name="condition"></param>
    /// <returns></returns>
    // todo
    public async Task<PaginatedList<AttrVo>> PageNationQuery(int pageIndex, int pageSize, int catalogID,
        string condition = "")
    {
        // 分页查询
        IOrderedQueryable<Attr> queryable = _attrMapper.GetAllAttrs()
            .Where(attr => (catalogID == 0 ? attr.CatalogID > 0 : attr.CatalogID == catalogID) &&
                           attr.AttrName.Contains(condition)).OrderBy(attr => attr.AttrID);
        PaginatedList<Attr> paginatedList = PaginatedList<Attr>.CreateAsync(queryable, pageIndex, pageSize).Result;

        List<Attr> attrs = paginatedList.Items;
        List<AttrVo> attrVos = new List<AttrVo>();

        foreach (Attr attr in attrs)
        {
            // 转换为vo
            AttrVo attrVo = JsonSerializer.Deserialize<AttrVo>(JsonSerializer.Serialize(attr))!;
            // 将属性值由字符串转换为string
            attrVo.AttrValue = attr.ValueSelect!.Split(";").ToList();
            // 查询分类名称
            Category category = await _categoryService.GetCategoryById(attr.CatalogID);
            attrVo.CategoryName = category.Name!;
            // 查询属性分组名称
            AttrGroupVo attrGroupVo = await _attrGroupService.GetAttrGroupByAttrId(attrVo.AttrID);
            attrVo.AttrGroupName = attrGroupVo.AttrGroupName!;
            attrVo.AttrGroupID = attrGroupVo.AttrGroupID;
            attrVos.Add(attrVo);
        }

        return new PaginatedList<AttrVo>(attrVos, attrs.Count, pageIndex, pageSize);
    }

    /// <summary>
    /// 根据分类id查询属性信息
    /// </summary>
    /// <param name="catalogId"></param>
    /// <returns></returns>
    public async Task<List<AttrVo>?> GetAttrByCatalogId(int catalogId)
    {
        List<Attr>? attrList = await _attrMapper.GetAttrByCategoryId(catalogId);
        return JsonSerializer.Deserialize<List<AttrVo>>(JsonSerializer.Serialize(attrList))!;
    }

    /// <summary>
    /// 修改属性值
    /// </summary>
    /// <param name="attrVo"></param>
    /// <returns></returns>
    public async Task<int> UpdateAttr(AttrVo attrVo)
    {
        using (TransactionScope transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            // 将属性值集合转换为字符串
            Attr attr = JsonSerializer.Deserialize<Attr>(JsonSerializer.Serialize(attrVo))!;
            attr.ValueSelect = string.Join(";", attrVo.AttrValue);
            await _attrMapper.UpdateAttr(attr);

            // 更新属性与属性分组的关联关系
            AttrAttrgroupRelation attrAttrgroupRelation = new AttrAttrgroupRelation()
                { AttrID = attrVo.AttrID, AttrGroupID = attrVo.AttrGroupID };
            int result = await _attrAttrGroupRelationService.UpdateAttrAttrGroupRelation(attrAttrgroupRelation);

            transactionScope.Complete();
            return result;
        }
    }

    /// <summary>
    /// 删除属性
    /// </summary>
    /// <param name="attrIds"></param>
    /// <returns></returns>
    public async Task<int> DeleteAttr(List<int> attrIds)
    {
        using (TransactionScope transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            // 删除属性与分组的关联关系
            _attrAttrGroupRelationService.DeleteAttrAttrGroupRelation(attrIds);
            // 删除属性
            int result = await _attrMapper.DeleteAttr(attrIds);
            
            transactionScope.Complete();
            return result;
        }
    }
}